'use strict';

/* Controllers */
// login controller
app.controller('SigninFormController',
    ['$rootScope', '$scope', '$http', '$state', '$cookies', '$cookieStore', '$translate',
        'server', 'errorUtilsService',
        function ($rootScope, $scope, $http, $state, $cookies, $cookieStore, $translate,
                  server, errorUtilsService) {
            // $scope.user = {cellphone: '11111111111', password: 'admin'};
            $scope.authError = null;
            $scope.login = function () {
                $scope.authError = null;
                // Try to login
                $http({
                    // withCredentials: true,
                    method: 'POST',
                    url: server.addr + '/user/login',
                    data: {
                        cellphone: $scope.user.cellphone,
                        password: $scope.user.password
                    }
                    // dataType: 'JSON'
                }).then(function (response) {
                    var sessionId = response.headers('book-session-id');
                    // var setCookie = response.headers('Set-Cookie');
                    if (sessionId) {
                        $cookies.sessionId = sessionId;
                        $cookieStore.put('book-session-id', sessionId);
                    }
                    angular.copy(response.data, $scope.user);
                    // store user in the cookie.
                    $cookieStore.put('book-user', $scope.user);
                    $rootScope.user = response.data;
                    $state.go('app.book.list');
                }, function (err) {
                    $scope.authError = errorUtilsService.parseErrorMsg(err, $translate.instant('strings.login.failure'));
                });
            };
        }]);